package com.lyz.dataStructure.xiancheng.多线程;

/**
 *@Author:759057893@qq.com Lyz
 *@Date: 2019/7/11 16:56
 *@Description:
 **/

/*
使用内部类设计四个线程，其中两个线程每次对j增加1，另外两个线程每次对j减少1
 */
public class ThreadDemo3 {
    private  int j;

    public static void main(String[] args) {
        ThreadDemo3 td = new ThreadDemo3();
        Inc inc = td.new Inc();
        Dec dec = td.new Dec();
        for(int i=0;i<2;i++){
            Thread t = new Thread(inc);
            t.start();
            t = new Thread(dec);
            t.start();
        }


    }

    class Inc implements Runnable{

        @Override
        public void run() {
            for(int i =0;i<20;i++){
                inc();
            }
        }
    }


    class Dec implements Runnable{

        @Override
        public void run() {
            for(int i =0;i<20;i++){
                dec();
            }
        }
    }


    private  void  inc(){
        synchronized(this){
            j++;
            System.out.println(Thread.currentThread().getName()+"-inc "+j);
        }
    }
    private  synchronized void  dec(){
        j--;
        System.out.println(Thread.currentThread().getName()+"-dec "+j);
    }
}
